package com.android.infantschool.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.FileProvider;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.infantschool.R;
import com.android.infantschool.app.InfantApp;
import com.android.infantschool.bean.BaseBean;
import com.android.infantschool.bean.DynamicBean;
import com.android.infantschool.bean.ReleaseDynamicBean;
import com.android.infantschool.model.config.AppConfig;
import com.android.infantschool.model.mvp.presenter.DynamicListPresenter;
import com.android.infantschool.model.mvp.presenter.DynamicListPresenterImpl;
import com.android.infantschool.model.mvp.view.DynamicListView;
import com.android.infantschool.ui.activity.BeautifulTeacherActivity;
import com.android.infantschool.ui.activity.ImageActivity;
import com.android.infantschool.ui.activity.PersonInfoActivity;
import com.android.infantschool.ui.activity.ReleaseDynamicActivity;
import com.android.infantschool.ui.activity.VideoActivity;
import com.android.infantschool.ui.adapter.DynamicAdapter;
import com.android.infantschool.ui.imageloader.GlideRoundTransform;
import com.android.infantschool.ui.view.SrcMenu;
import com.android.infantschool.util.Constant;
import com.android.infantschool.util.ToastUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * @author Administrator
 * @particulars
 * @time 2019\7\3 0003 13:08
 * @class describe  //显示发布动态模块
 */
public class DynamicFragment extends BaseFragment implements OnLoadMoreListener,
        OnRefreshListener, DynamicAdapter.OnLister, DynamicListView {

    private RelativeLayout rlTitle;
    private TextView tvTitle;
    private ImageView imgBack;
    private RecyclerView recyclerView;
    private SmartRefreshLayout refreshLayout;

    private DynamicAdapter dynamicAdapter;
    private SrcMenu srcMenu;
    private ImageView imgPlus;
    private RelativeLayout rlBeautifulTeacher;
    private RelativeLayout rlShan;

    private int REQUEST_GET_IMAGE = 1;
    private int REQUEST_GET_VIDEO = 2;
    private List<ReleaseDynamicBean> list = null;
    private DynamicListPresenter listPresenter = null;

    private int TYPE_PHONE = 1;//1:图片,2:视频
    private int pageNum = 0;//总页数
    private int pageNow = 1;//当前请求的第几页
    private boolean isRefresh = false;//false:刷新  true:加载

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_dynamic, container, false);
        initView(view);
        return view;
    }

    @Override
    public void onResume() {
        super.onResume();
        Glide.with(this).load(AppConfig.getUserPhoto())
                .override(150, 150)
                .transform(new CenterCrop(activity), new GlideRoundTransform(activity, 100))
                .into(imgBack);
    }

    private void initView(View view) {
        listPresenter = new DynamicListPresenterImpl(this);
        this.list = new ArrayList<>();
        rlTitle = view.findViewById(R.id.title);
        tvTitle = view.findViewById(R.id.tv_title);
        imgBack = view.findViewById(R.id.img_back);
        tvTitle.setText("动态");

        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(PersonInfoActivity.newIntent(activity));
            }
        });

        recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
        refreshLayout = (SmartRefreshLayout) view.findViewById(R.id.refreshLayout);
        imgPlus = (ImageView) view.findViewById(R.id.btn_plus);

        dynamicAdapter = new DynamicAdapter(activity, this);
        recyclerView.setLayoutManager(new LinearLayoutManager(activity));
        recyclerView.setAdapter(dynamicAdapter);

        this.showLoading();
        isRefresh = false;
        pageNow = 1;
        getDynamicList(pageNow);

        //设置 Footer 为 球脉冲 样式
        refreshLayout.setRefreshHeader(new ClassicsHeader(activity));
        refreshLayout.setRefreshFooter(new ClassicsFooter(activity));
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadMoreListener(this);
        srcMenu = (SrcMenu) view.findViewById(R.id.src_menu);
        rlBeautifulTeacher = (RelativeLayout) view.findViewById(R.id.rl_beautiful_teacher);
        rlShan = (RelativeLayout) view.findViewById(R.id.rl_shan);

        rlBeautifulTeacher.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(BeautifulTeacherActivity.newIntent(activity));
            }
        });

        srcMenu.setOnMenuItemClickListener(new SrcMenu.OnMenuItemClickListener() {
            @Override
            public void onClick(View view, int position) {//子菜单点击事件
                imgPlus.setImageResource(R.mipmap.icon_dynamic_edit);
                fadeOut(rlShan);
                if (position == 1) {
                    startVideo();
                }
                if (position == 2) {
                    startCameta();
                }
                if (position == 3) {
                    startActivity(ReleaseDynamicActivity.newIntent(activity, list));
                }
            }
        });

        srcMenu.setMainOnClickLister(new SrcMenu.OnMainClickListener() {
            @Override
            public void onClick() {//主菜单点击事件
                if (srcMenu.isOpen()) {//打开
                    imgPlus.setImageResource(R.mipmap.icon_dynamic_close);
                    fadeIn(rlShan);
                } else {//关闭
                    imgPlus.setImageResource(R.mipmap.icon_dynamic_edit);
                    fadeOut(rlShan);
                }
            }
        });
    }

    private void getDynamicList(int page) {
        Map<String, String> map = new HashMap<>();
        map.put("token", AppConfig.getToken());
        map.put("page", String.valueOf(page));
        map.put("limit", "5");
        Log.e(TAG, "map:" + map.toString());
        listPresenter.getDynamicList(map);
    }


    public static void fadeIn(View view, float startAlpha, float endAlpha, long duration) {
        if (view.getVisibility() == View.VISIBLE) return;
        view.setVisibility(View.VISIBLE);
        Animation animation = new AlphaAnimation(startAlpha, endAlpha);
        animation.setDuration(duration);
        view.startAnimation(animation);
    }

    /**
     * 隐藏到显示渐变
     *
     * @param view
     */
    public static void fadeIn(View view) {
        fadeIn(view, 0F, 1F, 500);
        view.setEnabled(true);
    }

    /**
     * 显示到隐藏渐变
     *
     * @param view
     */
    public static void fadeOut(View view) {
        if (view.getVisibility() != View.VISIBLE) return;
        view.setEnabled(false);
        Animation animation = new AlphaAnimation(1F, 0F);
        animation.setDuration(500);
        view.startAnimation(animation);
        view.setVisibility(View.GONE);
    }

    /**
     * 跳转到相册页
     */
    private void startCameta() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        UUID uuid = UUID.randomUUID();
        File file = new File(Constant.IMAGE_PATH(), uuid.toString() + ".jpeg");//拍照文件的路径
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri uri = FileProvider.getUriForFile(getContext(), "com.android.infantschool.fileprovider", file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        } else {
            Uri uri = Uri.fromFile(file);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, uri);
        }
        startActivityForResult(intent, REQUEST_GET_IMAGE);
    }

    /**
     * 启动相机，创建文件，并要求返回uri
     */
    private void startVideo() {
        Intent intent = new Intent();
        intent.setAction(MediaStore.ACTION_VIDEO_CAPTURE);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        File mVideoFile = createVideoFile();
        Log.e(TAG, "视频路径:" + mVideoFile.getAbsolutePath());
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri mVideoUri = null;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
            mVideoUri = FileProvider.getUriForFile(activity, "com.android.infantschool.fileprovider", mVideoFile);
        } else {
            mVideoUri = Uri.fromFile(mVideoFile);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, mVideoUri);
        startActivityForResult(intent, REQUEST_GET_VIDEO);
    }

    private String videoPath = "";

    /**
     * 创建视频文件
     */
    private File createVideoFile() {
        String mVideoName = Calendar.getInstance().getTimeInMillis() + ".mp4";
        File mVideoFile = new File(Constant.VIDEO_PATH(), mVideoName);
        mVideoFile.getParentFile().mkdirs();
        mVideoFile.setWritable(true);
        videoPath = mVideoFile.getAbsolutePath();
        return mVideoFile;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_GET_IMAGE && resultCode == Activity.RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumns = {MediaStore.Images.Media.DATA};
            Cursor c = activity.getContentResolver().query(selectedImage, filePathColumns, null, null, null);
            c.moveToFirst();
            int columnIndex = c.getColumnIndex(filePathColumns[0]);
            String picturePath = c.getString(columnIndex);
            Log.e(TAG, "图片路径:" + picturePath);
            if (this.list != null) {
                this.list.add(new ReleaseDynamicBean(picturePath, 1));
            }
            c.close();
            startActivity(ReleaseDynamicActivity.newIntent(activity, list));
        }

        if (requestCode == REQUEST_GET_VIDEO && resultCode == Activity.RESULT_OK && null != data) {
            Log.e(TAG, "filePath:" + videoPath);
            if (this.list != null) {
                this.list.add(new ReleaseDynamicBean(videoPath, 2));
            }
            startActivity(ReleaseDynamicActivity.newIntent(activity, list));
            if (list != null) {
                list.clear();
            }
        }
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        Log.e(TAG, "onDestroyView...");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (listPresenter != null) {
            listPresenter.onDestroy();
            listPresenter = null;
        }
    }

    @Override
    public void onLoadMore(@NonNull final RefreshLayout refreshLayout) {
        isRefresh = true;
        pageNow++;
        if (pageNow > pageNum) {//没有最新数据
            refreshLayout.finishLoadMore(true);
            refreshLayout.finishRefresh(true);
            return;
        }
        getDynamicList(pageNow);
    }

    @Override
    public void onRefresh(@NonNull final RefreshLayout refreshLayout) {
        isRefresh = false;
        pageNow = 1;
        getDynamicList(pageNow);
    }

    @Override
    public void listerImage(int position1, int position2) {
        DynamicBean.DataBean dynamicBean = dynamicAdapter.list.get(position1);
        if (dynamicBean.getUrlArray().get(position2).getType() == 1) {//看图片
            List<String> list = new ArrayList<>();
            for (int index = 0; index < dynamicBean.getUrlArray().size(); index++) {
                DynamicBean.DataBean.UrlArrayBean urlArrayBean = dynamicBean.getUrlArray().get(index);
                if (urlArrayBean.getType() == 1) {
                    list.add(urlArrayBean.getPath());
                }
            }
            startActivity(ImageActivity.newIntent(activity, position2, list));
        } else if (dynamicBean.getUrlArray().get(position2).getType() == 2) {//看视频
            DynamicBean.DataBean.UrlArrayBean arrayBean = dynamicBean.getUrlArray().get(position2);
            startActivity(VideoActivity.newIntent(activity, arrayBean.getPath()));
        }
    }

    @Override
    public void errorDynamicList(String error) {
        this.dismissLoading();
        refreshLayout.finishLoadMore(true);
        refreshLayout.finishRefresh(true);
        ToastUtil.showShortToast(activity, "网络异常:" + error);
    }

    @Override
    public void successDynamicList(BaseBean baseBean) {
        this.dismissLoading();
        refreshLayout.finishLoadMore(true);
        refreshLayout.finishRefresh(true);
        DynamicBean bean = (DynamicBean) baseBean;
        Log.e(TAG, "bean:" + bean.toString());
        if (bean.getCode() == 0) {
            pageNum = bean.getCount() / 5 + 1;//总条数
            if (isRefresh) {//加载
                dynamicAdapter.addData(bean.getData());
            } else {//刷新
                dynamicAdapter.setData(bean.getData());
            }
            Log.e(TAG, "size:" + dynamicAdapter.list.size());
        } else {
            ToastUtil.showShortToast(activity, bean.getMsg());
        }
    }
}